package com.wealth.scsj.p_app.view.activity.setting;

import android.app.Activity;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.res.Resources;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.app.ActivityCompat;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.Priority;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.vondear.rxtools.RxPermissionsTool;
import com.vondear.rxtools.RxPhotoTool;
import com.vondear.rxtools.RxSPTool;
import com.vondear.rxtools.view.dialog.RxDialogChooseImage;
import com.wealth.scsj.p_app.R;
import com.wealth.scsj.p_app.utils.CropCircleTransformation;
import com.wealth.scsj.p_app.utils.DialogUtils;
import com.wealth.scsj.p_app.utils.SkipUtils;
import com.wealth.scsj.p_app.view.activity.BaseActivity;
import com.wealth.scsj.p_app.view.activity.BillingRecordsActivity;
import com.yalantis.ucrop.UCrop;
import com.yalantis.ucrop.UCropActivity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import static com.vondear.rxtools.view.dialog.RxDialogChooseImage.LayoutType.TITLE;

/**
 * 设置页面
 */
public class SettingActivity extends BaseActivity implements View.OnClickListener {


    private ImageView mHeadIv;
    private RelativeLayout mHeadRl;
    private RelativeLayout mMyQrRl;
    /**
     * 156****6265
     */
    private TextView mMyPhoneNumTv;
    private RelativeLayout mChangePhonenumRl;
    /**
     * 修改
     */
    private TextView mLoginPasswordTv;
    private RelativeLayout mLoginPasswordRl;
    private RelativeLayout mRuleDescriptionRl;
    private RelativeLayout mCustomerServiceCenterRl;
    private RelativeLayout mFeedbackRl;
    /**
     * 当前版本V1.01
     */
    private TextView mCheckUpdateTv;
    private RelativeLayout mCheckUpdateRl;
    private RelativeLayout mAboutUsRl;
    private RelativeLayout mLogoutAccountRl;

    private Uri resultUri;

    @Override
    protected void createView(Bundle savedInstanceState) {
        setContentView(R.layout.activity_set);
        //ScreenAdapterTools.getInstance().loadView((ViewGroup) getWindow().getDecorView());
        //ScreenAdapterTools.getInstance().reset(this);//如果希望android7.0分屏也适配的话,加上这句
        initToolbar();
        setToolbarTitle("设置");
        hasBack(true);
    }

    @Override
    protected void initView() {

        mHeadIv = (ImageView) findViewById(R.id.head_iv);
        mHeadRl = (RelativeLayout) findViewById(R.id.head_rl);
        mHeadRl.setOnClickListener(this);
        mMyQrRl = (RelativeLayout) findViewById(R.id.my_qr_rl);
        mMyQrRl.setOnClickListener(this);
        mMyPhoneNumTv = (TextView) findViewById(R.id.my_phone_num_tv);
        mChangePhonenumRl = (RelativeLayout) findViewById(R.id.change_phonenum_rl);
        mChangePhonenumRl.setOnClickListener(this);
        mLoginPasswordTv = (TextView) findViewById(R.id.login_password_tv);
        mLoginPasswordRl = (RelativeLayout) findViewById(R.id.login_password_rl);
        mLoginPasswordRl.setOnClickListener(this);
        mRuleDescriptionRl = (RelativeLayout) findViewById(R.id.rule_description_rl);
        mRuleDescriptionRl.setOnClickListener(this);
        mCustomerServiceCenterRl = (RelativeLayout) findViewById(R.id.customer_service_center_rl);
        mCustomerServiceCenterRl.setOnClickListener(this);
        mFeedbackRl = (RelativeLayout) findViewById(R.id.feedback_rl);
        mFeedbackRl.setOnClickListener(this);
        mCheckUpdateTv = (TextView) findViewById(R.id.check_update_tv);
        mCheckUpdateRl = (RelativeLayout) findViewById(R.id.check_update_rl);
        mCheckUpdateRl.setOnClickListener(this);
        mAboutUsRl = (RelativeLayout) findViewById(R.id.about_us_rl);
        mAboutUsRl.setOnClickListener(this);
        mLogoutAccountRl = (RelativeLayout) findViewById(R.id.logout_account_rl);
        mLogoutAccountRl.setOnClickListener(this);
    }

    @Override
    protected void initListener() {

    }

    @Override
    protected void initData() {
        Resources r = this.getResources();
        resultUri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE + "://"
                + r.getResourcePackageName(R.drawable.ic_launcher_background) + "/"
                + r.getResourceTypeName(R.drawable.ic_launcher_background) + "/"
                + r.getResourceEntryName(R.drawable.ic_launcher_background));
    }


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
            case R.id.head_rl://头像
                RxPermissionsTool.with(this)
                        .addPermission(android.Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        .addPermission(android.Manifest.permission.CAMERA)
                        .initPermission();
                initDialogChooseImage();
                break;
            case R.id.my_qr_rl://我的二维码
                SkipUtils.toMyQRCode(this);
                break;
            case R.id.change_phonenum_rl://换绑手机
                SkipUtils.toAuthentication(this);
                break;
            case R.id.login_password_rl://登录密码
                SkipUtils.toChangeLoginPassword(this);
                break;
            case R.id.rule_description_rl://规则说明
                SkipUtils.toRuleDescription(this);
                break;
            case R.id.customer_service_center_rl://客服中心
                break;
            case R.id.feedback_rl://意见反馈
                SkipUtils.toSurveyFeedbackPage(this);
                break;
            case R.id.check_update_rl://检查更新
                Intent inten =new Intent();
                inten.setClass(SettingActivity.this,BillingRecordsActivity.class);
                startActivity(inten);
                break;
            case R.id.about_us_rl://关于我们
                //TODO 暂去登录页面
                SkipUtils.toLogin(this);
                break;
            case R.id.logout_account_rl://退出账户
                break;
        }
    }

    private void initDialogChooseImage() {
        RxDialogChooseImage dialogChooseImage = new RxDialogChooseImage(this, TITLE);
        dialogChooseImage.show();

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case RxPhotoTool.GET_IMAGE_FROM_PHONE://选择相册之后的处理
                if (resultCode == RESULT_OK) {
//                    RxPhotoTool.cropImage(ActivityUser.this, );// 裁剪图片
                    initUCrop(data.getData());
                }

                break;
            case RxPhotoTool.GET_IMAGE_BY_CAMERA://选择照相机之后的处理
                if (resultCode == RESULT_OK) {
                    /* data.getExtras().get("data");*/
//                    RxPhotoTool.cropImage(ActivityUser.this, RxPhotoTool.imageUriFromCamera);// 裁剪图片
                    initUCrop(RxPhotoTool.imageUriFromCamera);
                }

                break;
            case RxPhotoTool.CROP_IMAGE://普通裁剪后的处理
                Glide.with(this).
                        load(RxPhotoTool.cropImageUri).
                        diskCacheStrategy(DiskCacheStrategy.RESULT).
                        bitmapTransform(new CropCircleTransformation(this)).
                        thumbnail(0.5f).
                        placeholder(R.drawable.ic_launcher_background).
                        priority(Priority.LOW).
                        error(R.drawable.ic_launcher_background).
                        fallback(R.drawable.ic_launcher_background).
                        into(mHeadIv);
//                RequestUpdateAvatar(new File(RxPhotoTool.getRealFilePath(mContext, RxPhotoTool.cropImageUri)));
                break;

            case UCrop.REQUEST_CROP://UCrop裁剪之后的处理
                if (resultCode == RESULT_OK) {
                    resultUri = UCrop.getOutput(data);
                    roadImageView(resultUri, mHeadIv);
                    RxSPTool.putContent(this, "AVATAR", resultUri.toString());
                } else if (resultCode == UCrop.RESULT_ERROR) {
                    final Throwable cropError = UCrop.getError(data);
                }
                break;
            case UCrop.RESULT_ERROR://UCrop裁剪错误之后的处理
                final Throwable cropError = UCrop.getError(data);
                break;

            default:
                break;

        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private void initUCrop(Uri uri) {
        //Uri destinationUri = RxPhotoTool.createImagePathUri(this);

        SimpleDateFormat timeFormatter = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));

        Uri destinationUri = Uri.fromFile(new File(getCacheDir(), imageName + ".jpeg"));

        UCrop.Options options = new UCrop.Options();
        //设置裁剪图片可操作的手势
        options.setAllowedGestures(UCropActivity.SCALE, UCropActivity.ROTATE, UCropActivity.ALL);
        //设置隐藏底部容器，默认显示
        //options.setHideBottomControls(true);
        //设置toolbar颜色
        options.setToolbarColor(ActivityCompat.getColor(this, R.color.colorPrimary));
        //设置状态栏颜色
        options.setStatusBarColor(ActivityCompat.getColor(this, R.color.colorPrimaryDark));
        //开始设置
        //设置最大缩放比例
        options.setMaxScaleMultiplier(5);
        //设置图片在切换比例时的动画
        options.setImageToCropBoundsAnimDuration(666);
        //设置裁剪窗口是否为椭圆
        //options.setOvalDimmedLayer(true);
        //设置是否展示矩形裁剪框
        // options.setShowCropFrame(false);
        //设置裁剪框横竖线的宽度
        //options.setCropGridStrokeWidth(20);
        //设置裁剪框横竖线的颜色
        //options.setCropGridColor(Color.GREEN);
        //设置竖线的数量
        //options.setCropGridColumnCount(2);
        //设置横线的数量
        //options.setCropGridRowCount(1);
        UCrop.of(uri, destinationUri)
                .withAspectRatio(1, 1)
                .withMaxResultSize(1000, 1000)
                .withOptions(options)
                .start(this);
    }

    //从Uri中加载图片 并将其转化成File文件返回
    private File roadImageView(Uri uri, ImageView imageView) {
        Glide.with(this).
                load(uri).
                diskCacheStrategy(DiskCacheStrategy.RESULT).
                bitmapTransform(new CropCircleTransformation(this)).
                thumbnail(0.5f).
                placeholder(R.drawable.ic_launcher_background).
                priority(Priority.LOW).
                error(R.drawable.ic_launcher_background).
                fallback(R.drawable.ic_launcher_background).
                into(imageView);

        return (new File(RxPhotoTool.getImageAbsolutePath(this, uri)));
    }
}
